import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './types'
import tim from '@/framework/utils/tim.js';

Vue.use(Vuex)

const getPrefix=()=>{
  // //保存当前域名
  // var myHost=location.protocol+'//' + location.host
  // if (myHost.indexOf("localhost")>0){
  //   myHost="http://dev23.paoding.team"
  // }
  // return myHost+'/attachment/'
  return ''
}
const getMyHost=()=>{
  //保存当前域名
  var myHost=location.protocol+'//' + location.host
  if (myHost.indexOf("localhost")>0){
    myHost="http://dev23.paoding.team"
  }
  // return myHost + '/console/#'
  return myHost + '/web/#'
  // return 'http://localhost:8099/#/login/bind'
}
//表情前缀
const myEmojiPrefix=()=>{
  // 保存当前域名
  var myHost=location.protocol+'//' + location.host
  if (myHost.indexOf("localhost")>0){
    //本地时 图片前缀为
    myHost="http://dev18.paoding.team"
  }
  return myHost
}

const initPageState = () => {
  return {
    user: {
      realname: '' || JSON.parse(localStorage.getItem('managerCache')) ? JSON.parse(localStorage.getItem('managerCache')).realname : '',
      avatar: '' || JSON.parse(localStorage.getItem('managerCache')) ? JSON.parse(localStorage.getItem('managerCache')).avatar : '',
      id: '' || JSON.parse(localStorage.getItem('managerCache')) ? JSON.parse(localStorage.getItem('managerCache')).id : ''
    },
    prefix: getPrefix(),
    targetUrl: getMyHost(),
    // prefix: 'http://test3.paoding.team/attachment/',
    language: localStorage.language || 'zh',
    isAgreement: false,
    loginWay: 'password',
    currentChatId: localStorage.currentChatId || '',
    IM: {
      username: (localStorage.IMinfo && JSON.parse(localStorage.IMinfo).username) || "",
      userSig: (localStorage.IMinfo && JSON.parse(localStorage.IMinfo).userSig) || "",
    },
    messageList:[],
    chatType:'group',//聊天类型
    liveId: '',//直播id
    addProductList: [
      // {link: "1",price: "1",thumbnail: "image/logo1.jpg",title: "1",type: "link"},
      // {link: "2",price: "2",thumbnail: "image/logo1.jpg",title: "2",type: "link"},
      // {link: "3",price: "3",thumbnail: "image/logo1.jpg",title: "3",type: "link"},
    ],//添加商品的存储列表
    oldProductList: [],//保存旧商品数据的列表，上面的addProductList在条件搜索时会发生改变
    unRead:false,
    userList: [],//会话列表
    emojiPrefix:myEmojiPrefix() +"/attachment/",
  }
}
const store = new Vuex.Store({
  // strict: process.env.NODE_ENV !== 'production',
  state: initPageState(),
  mutations: {
    [types.SAVE_USER](state, pageState) {
      for (const prop in pageState) {
        state.user[prop] = pageState[prop]
      }
    },
    SAVE_LANG(state, lang) {
      state.language = lang
    },
    IS_AGREEMENT(state, isAgreement){
      state.isAgreement = isAgreement
    },
    LOGIN_WAY(state, loginWay){
      state.loginWay = loginWay
    },
    //备份商品列表
    saveOldProductList(state,list){
      state.oldProductList = list
    },
    //添加商品
    addProductList(state, list){
      state.addProductList = state.addProductList.concat(list)
    },
    //修改商品列表
    changeProductList(state, list){
      state.addProductList = list
    },
    //清空商品列表
    clearProductList(state){
      state.addProductList = []
    },
    //更新聊天信息
    updateMsgList(state, msgList) {
      // console.log('走到了store这里,更新消息列表',msgList.sendByOtherUser,state.currentChatId)
      // 判断当前有没有聊天的对象 避免未选择对象时 直接追加消息的bug
      console.log('本地的id:',localStorage.currentChatId)
      console.log('store的id:',state.currentChatId)

      if (!localStorage.currentChatId){
        return false
      }
      //收到别人发送的
      if(msgList.sendByOtherUser){
        console.log(msgList,'收到的消息')
        if( msgList.to === state.user.id && msgList.from === state.currentChatId){ //私聊，收到的消息为当前聊天对象的消息
          state.messageList.push(JSON.parse(JSON.stringify(msgList)))
        }else if(msgList.conversationType != "@TIM#SYSTEM"){ //群聊
          state.messageList.push(JSON.parse(JSON.stringify(msgList)))
        }
      }
      //自己发送给别人的
      else{
        if(msgList.to===state.currentChatId){
          state.messageList.push(JSON.parse(JSON.stringify(msgList)))
        }
      }
    },
    changeStateUnRead(state,payload){
      state.unRead = payload
    },
    //更新聊天用户列表
    updateUserList(state,payload){
      tim.getConversationList().then(res => {
        console.log(res.data.conversationList,'获取到的用户列表信息')
        let list = []
        res.data.conversationList.forEach(item => {
          if(item.type == 'C2C'){
            let obj = {
              id: item.userProfile.userID,
              nickname: item.userProfile.nick,
              avatar: item.userProfile.avatar,
              unreadCount: item.unreadCount,
              time: item.lastMessage.lastTime
            }
            list.push(obj)
          }
        })
        state.userList=JSON.parse(JSON.stringify(list))
        console.log('新的会话列表：',state.userList)
      }).catch(() => {
        // console.log('获取会话列表失败')
      })
      // state.userList=payload
    },
    //保存当前聊天的用户id
    SAVE_CURRENT_CHAT_ID(state, id) {
      state.currentChatId = id
    },
    //清除当前聊天的用户的id
    CLEAR_CURRENTCHAT_ID(state) {
      state.currentChatId = ''
    },
    SET_IM(state, value) {
      for (const prop in value) {
        state.IM[prop] = value[prop]
      }
    },
    // // 获取当前聊天对象的聊天内容
    // getMessageList(state,conversationID) {
    //   tim.getMessageList({conversationID, count: 15}).then(imReponse => {
    //     console.log('直播间id：'+conversationID)
    //     console.log('获取当前群聊的聊天内容',111111111,imReponse)
    //     // 更新当前消息列表，从头部插入
    //     // state.messageList = JSON.parse(JSON.stringify(imReponse.data.messageList))
    //     this.$store.commit('changeMessageList',JSON.parse(JSON.stringify(imReponse.data.messageList)))
    //     // return state.messageList
    //   })
    // },
    changeMessageList(state,list){
      state.messageList = list
      console.log('新的消息列表：',state.messageList)
    },
    //清除聊天内容
    clearMessageList(state){
      state.messageList=[]
    },
    chatType(state,value){
      state.chatType = value
    },
    LIVE_ID(state,value){
      state.liveId = value
    },
  },
  actions: {
    [types.SAVE_USER_CACHE]() {
      let user = this.state.user
      if (user.id !== '') {
        if (window.localStorage) {
          let ls = window.localStorage
          let managerCache = ls.getItem('managerCache')
          if (managerCache) {
            ls.removeItem('managerCache')
          }
          ls.setItem('managerCache', JSON.stringify(user))
        }
      }
    },
    [types.CLEAR_USER_CACHE]() {
      if (window.localStorage) {
        let ls = window.localStorage
        ls.removeItem('managerCache')
      }
    },
    [types.GET_USER_CACHE]() {
      if (window.localStorage) {
        let ls = window.localStorage
        let userStr = ls.getItem('managerCache')
        let user = JSON.parse(userStr)
        this.commit(types.SAVE_USER, {
          user: user
        })
      }
    },
    [types.GET_USER_EXIST]() {
      if (window.localStorage) {
        let ls = window.localStorage
        let userStr = ls.getItem('managerCache')
        return !!userStr
      }
    },
    //登录腾讯云
    onLogin: function(context,payload) {
      context.commit("SET_IM", payload)
      var options = {
        userID: payload.userID,
        userSig: payload.userSig,
        //appKey: WebIM.config.appkey,
      }
      console.log('登录腾讯云成功',options)
      //WebIM.conn.login(options)
      // 登录
      tim.login(options)

      localStorage.setItem("IMinfo", JSON.stringify({ userID: payload.userID, userSig: payload.userSig }))
    },
    // 获取当前聊天对象的聊天内容
    getMessageList: function(context,conversationID) {
      tim.getMessageList({conversationID, count: 15}).then(imReponse => {
        console.log('对象id：'+conversationID)
        console.log('获取当前群聊的聊天内容',111111111,imReponse)
        // 更新当前消息列表，从头部插入
        // let messageList = imReponse.data.messageList.slice()
        context.commit('changeMessageList',JSON.parse(JSON.stringify(imReponse.data.messageList)))
      })
    },
  }
})

export default store
